<?php
namespace App\Helpers\RSA;
use App\Helpers\Logger\SLogger;

/**
 * 日期转换类
 * Class DateUtils
 * @package App\Helpers
 */
class Rsa
{

    /**RSA签名函数
     * $data为待签名数据，比如URL
     * 签名用游戏方的保密私钥，必须是没有经过pkcs8转换的.结果需要用base64编码以备在URL中传输
     * return Sign 签名
     */

    public static function sign($data)
    {

//        //转换为openssl密钥，必须是没有经过pkcs8转换的私钥
        $pu_key = file_get_contents('key/public_key.pem');
//        dd($pu_key);
//        dd(openssl_pkey_get_public($pu_key));
        $pu_key = openssl_get_publickey($pu_key);


        //调用openssl内置签名方法，生成签名$sign

        openssl_public_encrypt($data,$sign,$pu_key,OPENSSL_ALGO_SHA1);//公钥加密

        openssl_free_key($pu_key);


        $sign = base64_encode($sign);

        return $sign;


    }

    public static function Sort($bean)
    {
        ksort($bean); // 按Key进行排序
        $s='';
        foreach ($bean as $key=>$val) {
            if ($val!= null) {
                $s=$s."&" .$key."=".$val;

            }
        }

        $s = sha1($s);
        return $s;
    }


    //ase加密
   public static function  encrypt($input, $key) {
       $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
       $input = self::pkcs5_pad($input, $size);
       $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
       //偏移量
       $iv = "0000000000000000";
       mcrypt_generic_init($td, $key, $iv);
       $data = mcrypt_generic($td, $input);
       mcrypt_generic_deinit($td);
       mcrypt_module_close($td);
       $data = base64_encode($data);
       return $data;
    }

public static function pkcs5_pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
}